package algotithm.leetcode.dfs.test47;

import java.util.*;

/**
 * @author zhouyanxiang
 * @Date 2021-04-2021/4/6-23:07
 * @Title 47. 全排列 II
 */
public class Solution {

    public static void main(String[] args) {
        int[] nums = {1,1,2};
        Solution solution = new Solution();
        List<List<Integer>> lists = solution.permuteUnique(nums);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Deque<Integer> path = new ArrayDeque<>();
        int len = nums.length;
        boolean[] used = new boolean[len];
        Arrays.sort(nums);
        dfs(nums,len,res,path,used,0);
        return res;
    }

    public void dfs(int[] nums,int len,List<List<Integer>> res, Deque<Integer> path,boolean[] used,int depth) {
        if (depth == len) {
            res.add(new ArrayList<>(path));
        }
        for (int i = 0; i < len; i++) {
            if (i > 0 && nums[i] == nums[i-1] && used[i-1]) {
                continue;
            }
            if (!used[i]) {
                path.addLast(nums[i]);
                used[i] = true;
                dfs(nums,len,res,path,used,depth+1);
                used[i] = false;
                path.removeLast();
            }
        }
    }

}
